#!/bin/bash

# Help function
function show_help {
    echo "Usage: md5c [-i|--input input_path] [-o|--output output_path] [-h|--help] [-v|--version]"
    echo "Options:"
    echo "  -i, --input input_path     Input path where .md5 files are located (default: current directory)."
    echo "  -o, --output output_path   Output path to save results (default: same as input path)."
    echo "  -h, --help                 Show this help message."
    echo "  -v, --version              Show script version."
    echo
    echo "Description:"
    echo "  This script performs MD5 checks on files located in the input_path."
    echo "  It compares the MD5 checksums in .md5 files with the actual file checksums."
    echo "  The results are saved in a file named 'md5_check_results.txt' in the output_path."
}

# Function to check if a directory exists
function dir_exists {
    local dir="$1"
    if [ ! -d "$dir" ]; then
        echo "Error: Directory '$dir' does not exist."
        exit 1
    fi
}

# Function to create a directory if it doesn't exist
function create_dir_if_not_exists {
    local dir="$1"
    if [ ! -d "$dir" ]; then
        mkdir -p "$dir"
        if [ $? -ne 0 ]; then
            echo "Error: Failed to create directory '$dir'."
            exit 1
        fi
    fi
}

# Function to check if a file exists
function file_exists {
    local file="$1"
    if [ ! -f "$file" ]; then
        echo "Error: File '$file' not found."
        exit 1
    fi
}

# Function to perform MD5 check for a single file
function perform_md5_check {
    local md5file="$1"
    local expected_md5
    local file_to_check
    local actual_md5
    local result

    expected_md5=$(cut -d " " -f 1 "$md5file")
    file_to_check="${md5file%.md5}"

    file_exists "$file_to_check"

    actual_md5=$(md5sum "$file_to_check" | cut -d " " -f 1)

    if [ "$expected_md5" = "$actual_md5" ]; then
        result="True"
    else
        result="False"
        has_false_result=true  # Set to true if a False result is found
    fi

    echo -e "$(basename "$file_to_check")\t$expected_md5\t$actual_md5\t$result" >> "$results_file"
}

# Initial configuration
config_file="$(dirname "$(dirname "$0")")/extdata/config.ini"
version="v$(grep "^\[md5c\]" -A 1 "$config_file" | grep "version" | cut -d "=" -f 2)"
current_date=$(date +"%Y%m%d")

# Check if no options are provided
if [ $# -eq 0 ]; then
    echo "Usage: md5c -h/--help for help."
    exit 1
fi

# Parse command line arguments
while getopts "i:o:hv" opt; do
    case $opt in
        i|--input_path)
            input_path="$OPTARG"
            ;;
        o|--output_path)
            output_path="$OPTARG"
            ;;
        h|--help)
            show_help
            exit 0
            ;;
        v|--version)
            echo "$version"
            exit 0
            ;;
        \?)
            echo "Invalid option: -$OPTARG" >&2
            exit 1
            ;;
        :)
            echo "Option -$OPTARG requires an argument." >&2
            exit 1
            ;;
    esac
done

# Check if no options are provided for input_path
if [ -z "$input_path" ]; then
    echo "Error: You must use the -i/--input option to specify an input path."
    exit 1
else
    # Check if the input directory exists
    dir_exists "$input_path"
fi

# Set default output path if not provided
if [ -z "$output_path" ]; then
    output_path="$input_path"
else
    create_dir_if_not_exists "$output_path"
fi

# Create the results file
results_file="$output_path/md5_check_results_$current_date.txt"
echo -e "File Name\tExpected MD5\tActual MD5\tResult" > "$results_file"

# Check if the results file was successfully created
if [ ! -f "$results_file" ]; then
    echo "Error: Failed to create results file '$results_file'."
    exit 1
fi

# Perform MD5 checks
has_false_result=false  # Initialize a variable to track False results

for md5file in $(find "$input_path" -name "*.md5"); do
    perform_md5_check "$md5file"
done

# Display results
cat "$results_file"

# Log results
if [ "$has_false_result" = false ]; then
    echo "MD5 Check Passed. Results saved to: $results_file"
else
    echo "MD5 Check Failed. Results saved to: $results_file"
fi
